package com.lisa.auto.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.*;
import com.lisa.auto.entity.c3.model.CarModelConfigure;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.VehicleMapper;
import com.lisa.auto.service.C3ExportLogService;
import com.lisa.auto.service.IVehicleService;
import com.lisa.auto.service.VehicleAreaService;
import com.lisa.auto.service.c3.C3CarModelConfigureService;
import com.lisa.auto.util.ExcelUtils;
import com.lisa.auto.util.basic.BaseException;
import com.lisa.auto.util.basic.BaseResponse;
import demo.C3ApiDemo;
import demo.request.VehicleCreateRequest;
import demo.request.VehicleUpdateRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 车辆信息 服务实现类
 * </p>
 *
 * @author huangzhigang
 * @since 2019-12-02
 */
@Service
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements IVehicleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(VehicleServiceImpl.class);

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Autowired
    private C3ExportLogService exportLogService;

    @Autowired
    private VehicleAreaService vehicleAreaService;
    @Autowired
    private C3CarModelConfigureService carModelConfigureService;

    public void createVehicles(Vehicle vehicle) {

        if (StringUtils.isEmpty(vehicle.getVin())) {
            throw new BaseException("车架号不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getPlateLicenseNo())) {
            throw new BaseException("车牌号不能为空");
        }
        vehicle.setGateWayNo("GW0000000000000000001504215038");
        //查询该车架号是否已存在，存在就更新，不存在就新增
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        ew.eq("vin", vehicle.getVin());
        List<Vehicle> vehicles = baseMapper.selectList(ew);
        if (vehicles != null && !vehicles.isEmpty()) {
            vehicle.setStatus(vehicle.getVehicleStatus());
            baseMapper.update(vehicle, ew);
        } else {
            baseMapper.insert(vehicle);
        }

//        new Thread(() -> {
//            LOGGER.info("新建车辆推送C3开始---------------");
//            try {
//                createVehicleToC3(vehicle);
//            } catch (Exception e) {
//                LOGGER.error("新建车辆推送C3失败---------------");
//            }
//            LOGGER.info("新建车辆推送C3结束---------------");
//        }).start();
    }

    @Override
    public void createVehicles(VehicleDto vehicleDto) {
        //先查找地区，看是否存在，拿到id
        VehicleArea vehicleArea = vehicleDto.getVehicleArea();
        Long id = vehicleAreaService.insertVehicleArea(vehicleArea);
        Vehicle vehicle = vehicleDto.getVehicle();
        vehicle.setAreaId(id);
        createVehicles(vehicle);
    }

    @Override
    public Page<Vehicle> getVehiclesList(Page<Vehicle> page) {
        EntityWrapper<Vehicle> ew = buildWrapper(page);
        List<Vehicle> vehiclesList = baseMapper.getVehiclesList(ew, page);
        page.setRecords(vehiclesList);
        return page;
    }

    private EntityWrapper<Vehicle> buildWrapper(Page<Vehicle> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        Map cd = page.getCondition();
        if (cd != null) {
            if (Objects.nonNull(cd.get("vin")) &&
                    StringUtils.isNotBlank(cd.get("vin").toString())) {
                ew.in("v.vin", cd.get("vin").toString().split(","));
            }
            if (Objects.nonNull(cd.get("plateLicenseNo")) &&
                    StringUtils.isNotBlank(cd.get("plateLicenseNo").toString())) {
                ew.like("v.plate_license_no", cd.get("plateLicenseNo").toString());
            }
            if (Objects.nonNull(cd.get("companyName")) &&
                    StringUtils.isNotBlank(cd.get("companyName").toString())) {
                ew.like("v.company", cd.get("companyName").toString());
            }
            if (Objects.nonNull(cd.get("powerType")) &&
                    StringUtils.isNotBlank(cd.get("powerType").toString())) {
                ew.eq("v.power_type", cd.get("powerType").toString());
            }
            if (Objects.nonNull(cd.get("status")) &&
                    StringUtils.isNotBlank(cd.get("status").toString())) {
                ew.eq("v.status", cd.get("status").toString());
            }
            if (Objects.nonNull(cd.get("province")) &&
                    StringUtils.isNotBlank(cd.get("province").toString())) {
                ew.eq("va.province", cd.get("province").toString());
            }
            if (Objects.nonNull(cd.get("city")) &&
                    StringUtils.isNotBlank(cd.get("city").toString())) {
                ew.eq("va.city", cd.get("city").toString());
            }
            if (Objects.nonNull(cd.get("county")) &&
                    StringUtils.isNotBlank(cd.get("county").toString())) {
                ew.eq("va.county", cd.get("county").toString());
            }
            if (Objects.nonNull(cd.get("startDate")) && StringUtils.isNotEmpty((String) cd.get("startDate"))) {
                ew.ge("v.gmt_create", cd.get("startDate").toString());
            }
            if (Objects.nonNull(cd.get("endDate")) && StringUtils.isNotEmpty((String) cd.get("endDate"))) {
                ew.le("v.gmt_create", cd.get("endDate").toString());
            }
        }
        ew.orderBy("v.gmt_create", Boolean.FALSE);
        return ew;
    }

    @Override
    public void updateVehicles(Vehicle vehicle) {
        EntityWrapper<Vehicle> ew = new EntityWrapper();
        if (vehicle != null) {
            if (Objects.nonNull(vehicle.getId()) && StringUtils.isNotEmpty(vehicle.getId().toString())) {
                ew.eq("id", vehicle.getId());
            } else {
                ew.eq("vin", vehicle.getVin());
            }
        }
        baseMapper.update(vehicle, ew);
    }


    @Override
    public void deleteVehicles(Vehicle vehicle) {
        try {
            EntityWrapper<Vehicle> ew = new EntityWrapper();
            ew.eq("vin", vehicle.getVin());
            vehicle.setIsDelete(1);
            baseMapper.update(vehicle, ew);
//        new Thread(() -> {
//            LOGGER.info("删除车辆推送C3开始---------------");
//            try {
//                deleteVehicleToC3(vehicle);
//            } catch (Exception e) {
//                LOGGER.error("删除车辆推送C3失败---------------");
//            }
//            LOGGER.info("删除车辆推送C3结束---------------");
//        }).start();
        } catch (Exception e) {
            LOGGER.error("VehicleServiceImpl.deleteVehicles ERROR {}", e.getMessage());
            throw new BaseException("删除车辆失败:" + e.getMessage());
        }
    }

    @Override
    public void updateStatusVehicles(String vin, String status) {
        if (vin == null || "".equals(vin)) {
            throw new BaseException("车架号不能为空");
        }
        baseMapper.updateStatusVehicles(vin, status);
    }


    /**
     * 新增车辆推C3
     *
     * @param vehicle
     */
    private void createVehicleToC3(Vehicle vehicle) {
        C3ExportLog exportLog = new C3ExportLog();
        try {
            String url = c3url + C3UrlEnum.VEHICLESURL.getUrl();
            VehicleCreateRequest request = new VehicleCreateRequest();
            BeanUtils.copyProperties(vehicle, request);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            exportLog.setInterfaceUrl(url);
            exportLog.setExportKey(vehicle.getVin());
            exportLog.setExportType("CREATE_VEHICLE");
            exportLog.setTargetSys("C3");
            exportLog.setDataContent(requstJson);
            String result = C3ApiDemo.post(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Vehicle> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("新增车辆失败:" + baseResponse.getReturnErrMsg());
                }
                exportLog.setExportStatus("1");
                exportLog.setExportResponse(result);
            }
            getVehicleForC3(vehicle.getVin());
        } catch (Exception e) {
            LOGGER.error("VehicleServiceImpl.createVehicleToC3 ERROR {}", e.getMessage());
            exportLog.setExportStatus("0");
            exportLog.setExportResponse(e.getMessage());
        }
        exportLogService.insert(exportLog);
    }


    /**
     * 更新车辆推C3
     *
     * @param vehicle
     */
    private void updateVehicleToC3(Vehicle vehicle) {
        try {
            String url = c3url + C3UrlEnum.VEHICLESURL.getUrl();
            VehicleUpdateRequest request = new VehicleUpdateRequest();
            BeanUtils.copyProperties(vehicle, request);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.put(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Vehicle> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("更新车辆失败:" + baseResponse.getReturnErrMsg());
                }
                createVehicles(baseResponse.getData());
            }
        } catch (Exception e) {
            LOGGER.error("VehicleServiceImpl.updateVehicleToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }


    /**
     * 删除车辆推C3
     *
     * @param vehicle
     */
    private void deleteVehicleToC3(Vehicle vehicle) {
        try {
            String url = c3url + C3UrlEnum.VEHICLESURL.getUrl();
            VehicleCreateRequest request = new VehicleCreateRequest();
            BeanUtils.copyProperties(vehicle, request);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.delete(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Vehicle> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("删除车辆失败:" + baseResponse.getReturnErrMsg());
                }
                deleteVehicles(baseResponse.getData());
            }
        } catch (Exception e) {
            LOGGER.error("VehicleServiceImpl.deleteVehicleToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 查询车辆详细信息
     *
     * @param
     */
    private void getVehicleForC3(String vin) {
        C3ExportLog exportLog = new C3ExportLog();
        try {
            String url = c3url + C3UrlEnum.VEHICLESURL.getUrl();
            VehicleCreateRequest request = new VehicleCreateRequest();
            request.setVin(vin);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            exportLog.setInterfaceUrl(url);
            exportLog.setExportKey(vin);
            exportLog.setExportType("GET_VEHICLE");
            exportLog.setTargetSys("C3");
            exportLog.setDataContent(requstJson);
            String result = C3ApiDemo.get(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Vehicle> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("获取车辆信息失败:" + baseResponse.getReturnErrMsg());
                }
                exportLog.setExportStatus("1");
                exportLog.setExportResponse(result);
                EntityWrapper<Vehicle> ew = new EntityWrapper<>();
                ew.eq("vin", vin);
                baseMapper.update(baseResponse.getData(), ew);
            }
        } catch (Exception e) {
            LOGGER.error("VehicleServiceImpl.getVehicleForC3 ERROR {}", e.getMessage());
            exportLog.setExportStatus("0");
            exportLog.setExportResponse(e.getMessage());
        }
        exportLogService.insert(exportLog);
    }

    @Override
    public void forbiddenByIds(String ids) {
        if (StringUtils.isEmpty(ids)) throw new BaseException("参数为空");
        String[] split = ids.split(",");
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        ew.in("id", split);
        List<Vehicle> vehicles = baseMapper.selectList(ew);
        if (vehicles == null || vehicles.size() < 1) throw new BaseException("未查询到对应车辆信息");
        for (Vehicle vehicle : vehicles) {
            if ("50".equals(vehicle.getStatus())) throw new BaseException("存在已删除车辆");
            if ("40".equals(vehicle.getStatus())) throw new BaseException("存在已禁用车辆");
        }
        Vehicle info = new Vehicle();
        info.setStatus("40");
        baseMapper.update(info, ew);
    }

    @Override
    public void enableByIds(String ids) {
        if (StringUtils.isEmpty(ids)) throw new BaseException("参数为空");
        String[] split = ids.split(",");
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        ew.in("id", split);
        List<Vehicle> vehicles = baseMapper.selectList(ew);
        if (vehicles == null || vehicles.size() < 1) throw new BaseException("未查询到对应车辆信息");
        for (Vehicle vehicle : vehicles) {
            if ("50".equals(vehicle.getStatus())) throw new BaseException("存在已删除车辆");
            if ("10".equals(vehicle.getStatus())) throw new BaseException("存在已启用车辆");
        }
        Vehicle info = new Vehicle();
        info.setStatus("10");
        baseMapper.update(info, ew);
    }

    @Override
    public void deleteByIds(String ids) {
        if (StringUtils.isEmpty(ids)) throw new BaseException("参数为空");
        String[] split = ids.split(",");
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        ew.in("id", split);
        List<Vehicle> vehicles = baseMapper.selectList(ew);
        if (vehicles == null || vehicles.size() < 1) throw new BaseException("未查询到对应车辆信息");
        for (Vehicle vehicle : vehicles) {
            if ("50".equals(vehicle.getStatus())) throw new BaseException("存在已删除车辆");
        }
        Vehicle info = new Vehicle();
        info.setStatus("50");
        baseMapper.update(info, ew);
    }

    @Override
    public void importVehicleExcel(MultipartFile file, HttpServletResponse response) {
        try {
            String param0 = "{\"制造商\":\"makerName\",\"品牌\":\"brandName\",\"车系\":\"seriesName\",\"车型\":\"modelName\",\"车牌号\":\"plateLicenseNo\",\"车架号\":\"vin\",\"省\":\"province\",\"市\":\"city\",\"区/县\":\"county\",\"备注\":\"mark\"}";
            List<VehiclePo> vehiclePoList = ExcelUtils.readExcel(file.getInputStream(), VehiclePo.class, param0, null);
            System.out.println(vehiclePoList);
            List<Vehicle> list = new ArrayList<>();
            for (VehiclePo vehiclePo : vehiclePoList) {
                if (vehiclePo == null) {
                    continue;
                }
                if (vehiclePo.getVin() != null && !"".equals(vehiclePo.getVin()) && !"0".equals(vehiclePo.getVin())) {
                    Vehicle vehicle = new Vehicle();
                    VehicleArea vehicleArea = new VehicleArea();
                    vehicleArea.setProvince(vehiclePo.getProvince());
                    vehicleArea.setCity(vehiclePo.getCity());
                    vehicleArea.setCounty(vehiclePo.getCounty());
                    Long id = vehicleAreaService.insertVehicleArea(vehicleArea);
                    vehicle.setAreaId(id);
                    vehicle.setVin(vehiclePo.getVin());
                    vehicle.setPlateLicenseNo(vehiclePo.getPlateLicenseNo());
                    vehicle.setBrandName(vehiclePo.getBrandName());
                    vehicle.setSeriesName(vehiclePo.getSeriesName());
                    vehicle.setMakerName(vehiclePo.getMakerName());
                    vehicle.setModelName(vehiclePo.getModelName());
                    //根据车型名查询车型编号
                    Map<String, Object> map = new HashMap<>();
                    map.put("modelName",vehiclePo.getModelName());
                    List<CarModelConfigure> configuresList = carModelConfigureService.getConfiguresList(map);
                    if (configuresList!=null && configuresList.size()>0){
                        vehicle.setModelNo(configuresList.get(0).getModelNo());
                    }
                    createVehicles(vehicle);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Page<VehicleModelConfigureDto> getVehiclesListNew(Page<VehicleModelConfigureDto> page) {
        EntityWrapper<VehicleModelConfigureDto> ew = buildWrapper2(page);
        List<VehicleModelConfigureDto> vehiclesList = baseMapper.getVehiclesListNew(ew, page);
        page.setRecords(vehiclesList);
        return page;
    }

    @Override
    public List<String> getVehiclesFleet(String fleet ) {
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        if (StringUtils.isNotEmpty(fleet)){
            ew.like("fleet",fleet);
        }
        return baseMapper.getVehiclesFleet(ew);
    }

    @Override
    public Object vehiclesToC3(Vehicle vehicle) {
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        ew.eq("vin",vehicle.getVin());
        List<Vehicle> vehicles = baseMapper.selectList(ew);
        createVehicleToC3(vehicles.get(0));
        return null;
    }

    @Override
    public List<String> getPlateList(Map<String,String> map) {
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        if (map!=null){
            if (StringUtils.isNotEmpty(map.get("fleet"))){
                ew.eq("fleet",map.get("fleet"));
            }
            if (StringUtils.isNotEmpty(map.get("plate"))){
                ew.like("plate_license_no",map.get("plate"));
            }
        }
        return baseMapper.getPlateList(ew);
    }

    private EntityWrapper<VehicleModelConfigureDto> buildWrapper2(Page<VehicleModelConfigureDto> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<VehicleModelConfigureDto> ew = new EntityWrapper<>();
        Map cd = page.getCondition();
        if (cd != null) {
            if (Objects.nonNull(cd.get("vin")) &&
                    StringUtils.isNotBlank(cd.get("vin").toString())) {
                ew.in("v.vin", cd.get("vin").toString().split(","));
            }
            if (Objects.nonNull(cd.get("plateLicenseNo")) &&
                    StringUtils.isNotBlank(cd.get("plateLicenseNo").toString())) {
                ew.like("v.plate_license_no", cd.get("plateLicenseNo").toString());
            }
            if (Objects.nonNull(cd.get("fleet")) &&
                    StringUtils.isNotBlank(cd.get("fleet").toString())) {
                ew.like("v.fleet", cd.get("fleet").toString());
            }
            if (Objects.nonNull(cd.get("makerName")) &&
                    StringUtils.isNotBlank(cd.get("makerName").toString())) {
                ew.like("v.maker_name", cd.get("makerName").toString());
            }
            if (Objects.nonNull(cd.get("brandName")) &&
                    StringUtils.isNotBlank(cd.get("brandName").toString())) {
                ew.like("v.brand_name", cd.get("brandName").toString());
            }
            if (Objects.nonNull(cd.get("seriesName")) &&
                    StringUtils.isNotBlank(cd.get("seriesName").toString())) {
                ew.like("v.series_name", cd.get("seriesName").toString());
            }
            if (Objects.nonNull(cd.get("modelName")) &&
                    StringUtils.isNotBlank(cd.get("modelName").toString())) {
                ew.like("v.model_name", cd.get("modelName").toString());
            }
            if (Objects.nonNull(cd.get("status")) &&
                    StringUtils.isNotBlank(cd.get("status").toString())) {
                ew.eq("v.status", cd.get("status").toString());
            }
            if (Objects.nonNull(cd.get("startDate")) && StringUtils.isNotEmpty((String) cd.get("startDate"))) {
                ew.ge("v.gmt_create", cd.get("startDate").toString());
            }
            if (Objects.nonNull(cd.get("endDate")) && StringUtils.isNotEmpty((String) cd.get("endDate"))) {
                ew.le("v.gmt_create", cd.get("endDate").toString());
            }
        }
        ew.orderBy("v.gmt_create", Boolean.FALSE);
        return ew;
    }

}
